package servlet;

import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload")
public class FileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    /**
     * 处理文件上传请求
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查是否为文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是文件上传请求，返回错误响应
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }

        // 配置文件上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 创建上传目录
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 解析请求的内容，提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 处理每个上传的文件项
                for (FileItem item : formItems) {
                    if (!item.isFormField()) { // 如果是文件类型的表单字段
                        // 生成唯一的文件名
                        String fileName = UUID.randomUUID().toString() + "-" + item.getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        System.out.println("文件保存路径：" + storeFile.getAbsolutePath());

                        // 保存文件到硬盘
                        item.write(storeFile);

                        // 构建文件的URL路径
                        String fileUrl = request.getRequestURL().toString().replace(request.getRequestURI(), "")
                                + request.getContextPath() + "/" + UPLOAD_DIRECTORY + "/" + fileName;

                        // 返回上传成功的文件URL
                        response.setContentType("application/json");
                        PrintWriter out = response.getWriter();
                        out.print("{\"code\":200,\"message\":\"文件上传成功\",\"data\":\"" + fileUrl + "\"}");
                        out.flush();
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.print("{\"code\":500,\"message\":\"文件上传失败\"}");
            out.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.print("{\"code\":500,\"message\":\"文件上传失败\"}");
            out.flush();
        }
    }
}
